// 日志sdk

class logger {
  constructor(ctx) {
    ctx = ctx || {};
    if (!ctx || typeof ctx._emitter != "object") {
      throw new Error('初始化消息发送器模块时，请传入_emitter对象');
    }
    // 根据参数判定logger是否显示
    this._loggerShow = ctx.loggerShow || false;
    this._mfutil = ctx._that || "";
    this._emitter = ctx._emitter || "";  // 发送消息对象
    this._loggerArray = [{
      name: "日志",
      tag: 1,
      logArray: []
    },
    {
      name: "网络",
      tag: 2,
      logArray: []
    },
    {
      name: "分享",
      tag: 3,
      logArray: []
    },
    {
      name: "抽奖",
      tag: 4,
      logArray: []
    }];
    // 如果不需要显示去取一下用户的白名单
    if (!this._loggerShow) {
      this.getUserLoggerShow();
    }
  }

  //  消息发送器
  async set({ origin, msg }) {
    if (!this._emitter) {
      return console.log("_emitter对象不存在，请在初始化时传入");
    }
    let msgstr = typeof msg == "string" ? msg : JSON.stringify(msg);
    this._loggerArray[0].logArray.push({
      origin: origin,
      data: msgstr
    });
    this._emitter.emit("logger-topic", { data: this._loggerArray });
    return true;
  }

  // 获取消息
  async get() {
    return this._loggerArray;
  }

  // 获取用户信息
  async getUserLoggerShow() {
    let userInfo = await this._mfutil.userAccess.get();

    if (userInfo && userInfo.success && userInfo.data && userInfo.data.length && userInfo.data[0] && userInfo.data[0].loggerShow) {
      this._loggerShow = true;
      this._emitter.emit('changeLoggerShow');
    }
  }

  // 获取 LoggerShow
  async getLoggerShow() {
    return this._loggerShow;
  }

  // 设置 LoggerShow
  async setLoggerShow(loggerShow = true) {
    this._loggerShow = loggerShow;
    this._emitter.emit('changeLoggerShow');
  }

}

module.exports = exports.logger = logger;